using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace System {
	public class PostQueryStr {
		Inputs _inps;
		public PostQueryStr(Inputs inps) {
			_inps=inps;
		}
		List<string> list=new List<string>();
		public void Add(string k) {
			string v=_inps[k];
			list.Add(string.Format("{0}={1}",HttpUtility.UrlEncode(k),HttpUtility.UrlEncode(v)));
		}
		public void Add(string k,string v) {
			list.Add(string.Format("{0}={1}",HttpUtility.UrlEncode(k),HttpUtility.UrlEncode(v)));
		}
		public override string ToString() {
			return string.Join("&",list.ToArray());
		}
	}
	public class Inputs {
		public string frmAction;
		Dictionary<string,string> vals=new Dictionary<string,string>();
		public Inputs(string src) {
			string frm=Nod.Rx(src,"<form.+?>");
			frmAction=Nod.Rx(frm,"action=\"(.+?)\"");

			string[] inps=Nod.Rxs(src,"<input.+?/>");
			foreach(string inp in inps)
			{
				string name=Nod.Rx(inp,"name=\"(.+?)\"");
				if(name!=null)
				{
					string val=Nod.Rx(inp,"value=\"(.*?)\"");
					vals.Add(name,val);
				}
			}
		}
		public string this[string key] {
			get {
				return vals[key];
			}
		}
	}

	public class PostLoader {
		public CookieContainer con=new CookieContainer();
		string referrer="";
		string userAgent="Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/23.0";
		public string Get(string url) {
			string ret="";
			HttpWebRequest httpWReq=(HttpWebRequest)WebRequest.Create(url);
			httpWReq.CookieContainer=con;
			httpWReq.Referer=referrer;
			httpWReq.UserAgent=userAgent;
			httpWReq.Proxy.Credentials=CredentialCache.DefaultCredentials;
			UTF8Encoding encoding=new UTF8Encoding();
			httpWReq.Method="GET";
			using(HttpWebResponse resp=(HttpWebResponse)httpWReq.GetResponse())
			using(StreamReader rdr=new StreamReader(resp.GetResponseStream()))
				ret=rdr.ReadToEnd();
			referrer=url;
			return ret;
		}

		public string Post(string url,string postData) {
			string ret="";
			HttpWebRequest httpWReq=(HttpWebRequest)WebRequest.Create(url);
			httpWReq.CookieContainer=con;
			httpWReq.Referer=referrer;
			httpWReq.UserAgent=userAgent;
			httpWReq.Proxy.Credentials=CredentialCache.DefaultCredentials;
			UTF8Encoding encoding=new UTF8Encoding();
			byte[] bdata=encoding.GetBytes(postData);
			httpWReq.Method="POST";
			httpWReq.ContentType="application/x-www-form-urlencoded";
			httpWReq.ContentLength=bdata.Length;
			httpWReq.GetRequestStream().Write(bdata,0,bdata.Length);
			using(HttpWebResponse resp=(HttpWebResponse)httpWReq.GetResponse())
			using(StreamReader rdr=new StreamReader(resp.GetResponseStream()))
				ret=rdr.ReadToEnd();
			//File.WriteAllText("C:\\test.htm",ret);
			referrer=url;
			return ret;
		}
	}
}
